package pers.cj.pdos.controller.other;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.cj.pdos.controller.base.BaseController;
import pers.cj.pdos.controller.entity.ResponseData;
import pers.cj.pdos.controller.entity.ResponseList;
import pers.cj.pdos.entity.Attr;
import pers.cj.pdos.entity.BusinessSet;
import pers.cj.pdos.entity.Company;
import pers.cj.pdos.entity.GoodsStock;
import pers.cj.pdos.excel.ExcelHouseQuery;
import pers.cj.pdos.excel.ExcelHouseQueryDetail;
import pers.cj.pdos.excel.ExcelInGoods;
import pers.cj.pdos.service.IGoodsService;
import pers.cj.pdos.service.IGoodsStockService;
import pers.cj.pdos.service.IHouseService;
import pers.cj.pdos.service.IStoreService;
import pers.cj.pdos.task.CleanTempExcelTask;
import pers.cj.pdos.utils.*;
import pers.cj.pdos.vo.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 库存查询
 */
@Controller
@RequestMapping("/house")
public class HouseQueryController extends BaseController {
    @Autowired
    IGoodsStockService goodsStockService;
    @Autowired
    IGoodsService goodsService;
    @Autowired
    IStoreService storeService;
    @Autowired
    IHouseService houseService;

    @RequiresPermissions("houseQuery:query")
    @RequestMapping("/houseQuery")
    public String houseQuery(){
        return "houseQuery/houseQuery";
    }


    @RequiresPermissions("houseQuery:water")
    @RequestMapping("/houseQueryDetail")
    public String houseQueryDetail(Model model, String goodsId, String storeId, String houseId){
        model.addAttribute(goodsService.getVoById(goodsId));

        model.addAttribute("storeId",storeId);
        model.addAttribute("houseId",houseId);

        if (!Utils.isEmpty(storeId)) {
            model.addAttribute("storeName",storeService.getById(storeId).getName());
        }

        if (!Utils.isEmpty(houseId)) {
            model.addAttribute("houseName",houseService.getById(houseId).getName());
        }
        return "houseQuery/houseQueryDetail";
    }

    @ResponseBody
    @RequiresPermissions("houseQuery:query")
    @RequestMapping("/houseQuery/getList")
    public ResponseList getList(String page,
                                String limit,
                                String goodsTypeId,
                                String goodsStatus,
                                String filterZero,
                                String search,
                                String storeId,
                                String houseId){
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<GoodsVo> list = goodsStockService.listVo(company.getId(),
                Utils.genInteger(page),
                Utils.genInteger(limit),
                goodsTypeId,
                Utils.genInteger(goodsStatus),
                Utils.genBoolean(filterZero),
                Utils.genLikeData(search),
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId);
        long count = goodsStockService.count(company.getId(),
                goodsTypeId,
                Utils.genInteger(goodsStatus),
                Utils.genBoolean(filterZero),
                Utils.genLikeData(search),
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId);
        return ResponseList.success(count,list);
    }

    @ResponseBody
    @RequiresPermissions("houseQuery:water")
    @RequestMapping("/houseQuery/listDetailListByGoods")
    public ResponseList listDetailListByGoods(String page,
                                              String limit,
                                              String storeId,
                                              String houseId,
                                              String goodsId,
                                              String search){
        if (Utils.isEmpty(goodsId)) {
            return ResponseList.fail("商品id不能为空");
        }
        UserVo userVo = getLoginUserVo();
        List<HouseQueryDetailVo> list = goodsStockService.listDetailListByGoods(Utils.genInteger(page),
                Utils.genInteger(limit),
                goodsId,
                Utils.genLikeData(search),
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId);
        long count = goodsStockService.countDetailListByGoods(goodsId,
                Utils.genLikeData(search),
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId);
        return ResponseList.success(count,list);
    }

    /**
     * 先更具请求数据
     * @throws IOException
     */
    @ResponseBody
    @RequiresPermissions("houseQuery:export")
    @RequestMapping("/houseQuery/export")
    public ResponseData export(String goodsTypeId,
                               String goodsStatus,
                               String filterZero,
                               String search,
                               String storeId,
                               String houseId){
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();
        List<GoodsVo> list = goodsStockService.listVo(company.getId(),
                null,
                null,
                goodsTypeId,
                Utils.genInteger(goodsStatus),
                Utils.genBoolean(filterZero),
                Utils.genLikeData(search),
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId);

        String fileName = "库存统计" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path+fileName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX,true);
            Sheet sheet1 = new Sheet(1,0, ExcelHouseQuery.class);
            sheet1.setSheetName("库存统计信息");
            writer.write(genExcelList(list), sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(fileName,new Date().getTime());
            return ResponseData.success(fileName);
        } catch (IOException e) {
            return ResponseData.fail("订单列表导出失败");
        }
    }

    /**
     * 先更具请求数据
     * @param goodsId
     * @throws IOException
     */
    @ResponseBody
    @RequiresPermissions("houseQuery:export")
    @RequestMapping("/houseQueryDetail/export")
    public ResponseData detailExport(String goodsId, String search, String storeId, String houseId) {
        UserVo userVo = getLoginUserVo();
        List<HouseQueryDetailVo> list = goodsStockService.listDetailListByGoods(null,
                null,
                goodsId,
                Utils.genLikeData(search),
                PdosUtils.getViewOtherStoreId(userVo,storeId),
                houseId);

        String fileName = "库存流水列表" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path+fileName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX,true);
            Sheet sheet1 = new Sheet(1,0, ExcelHouseQueryDetail.class);
            sheet1.setSheetName("库存流水信息");
            writer.write(genDetailExcelList(list), sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(fileName,new Date().getTime());
            return ResponseData.success(fileName);
        } catch (IOException e) {
            return ResponseData.fail("订单列表导出失败");
        }
    }

    private List<ExcelHouseQueryDetail> genDetailExcelList(List<HouseQueryDetailVo>  houseQueryDetailVoList) {
        List<ExcelHouseQueryDetail> list = new ArrayList<>();

        for (HouseQueryDetailVo vo : houseQueryDetailVoList){
            ExcelHouseQueryDetail excel = new ExcelHouseQueryDetail();
            excel.setDate(DateUtils.getDate(vo.getDate(), DateUtils.YYYY_MM_DD));
            excel.sethNo(vo.gethNo());
            excel.setNo(vo.getNo());
            excel.setStore(vo.getStoreName());
            excel.setHouse(vo.getHouseName());
            excel.setTypeName(vo.getTypeName());
            excel.setUnit(vo.getUnitName());
            excel.setOutNumber(vo.getOutNumber().toString());
            excel.setInNumber(vo.getInNumber().toString());
            excel.setStatus(vo.getClose() ? "作废":"");
            list.add(excel);
        }

        return  list;
    }

    private List<ExcelHouseQuery> genExcelList(List<GoodsVo> goodsVoList) {
        List<ExcelHouseQuery> list = new ArrayList<>();
        BusinessSet businessSet = getBusinessSet();
        for (GoodsVo vo : goodsVoList){
            ExcelHouseQuery excel = new ExcelHouseQuery();

            GoodsUnitVo goodsUnitVo = vo.getGoodsUnitVoList().get(0);
            excel.setNo(vo.getNo());
            excel.setName(vo.getName());
            excel.setType(vo.getType().getName());

            excel.setNorms(vo.getNorms());
            if (!Utils.isEmpty(vo.getAttrNameVoList())) {
                StringBuilder attrs = new StringBuilder();
                for (AttrNameVo attrNameVo : vo.getAttrNameVoList()) {
                    attrs.append(attrNameVo.getName()+":");
                    String attrStr="";

                    if (!Utils.isEmpty(attrNameVo.getAttrList())) {
                        for (Attr attr : attrNameVo.getAttrList()) {
                            attrStr += attr.getAttrValue()+"、";
                        }
                        attrStr = attrStr.substring(0,attrStr.length()-1);
                    }

                    attrs.append(attrStr);
                    attrs.append(";");
                }
                String attr = attrs.toString();
                attr = attr.substring(0,attr.length()-1);
                excel.setAttr(attr);
            }



            excel.setUnit(goodsUnitVo.getUnit().getName());
            excel.setCode(goodsUnitVo.getCode());

            BigDecimal stock = new BigDecimal(0);
            for (GoodsStockVo goodsStockVo : vo.getGoodsStockVoList()) {
                stock = stock.add(goodsStockVo.getNum());
            }

            excel.setStock(stock.toString());
            excel.setReferBuyPrice(goodsUnitVo.getReferBuyPrice().setScale(businessSet.getPricePoint()).toString());
            excel.setCost(vo.getCost().setScale(businessSet.getPricePoint()).toString());
            excel.setTotalCost(vo.getCost().multiply(stock).setScale(businessSet.getPricePoint()).toString());
            excel.setRetail(goodsUnitVo.getRetailPrice().setScale(businessSet.getPricePoint()).toString());
            excel.setTotalRetail(goodsUnitVo.getRetailPrice().multiply(stock).setScale(businessSet.getPricePoint()).toString());
            list.add(excel);
        }
        return list;
    }
}
